package com.news.web.servlet.admin;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;

/**
 * Servlet implementation class AdminUserDeleteAllServlet
 */
@WebServlet("/AdminUserDeleteAllServlet")
public class AdminUserDeleteAllServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 设置编码方式
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 创建UserService实例
		UserService userService = new UserServiceImpl();
		// 获取需要删除的id
		String[] userIdStr = request.getParameterValues("userIdAll");
		if (userIdStr != null) {
		    int[] userIds = new int[userIdStr.length];
		    for (int i = 0; i < userIdStr.length; i++) {
		    	// 执行异常抛出，加入传入的str不能转为数字
				try {
					userIds[i] = Integer.parseInt(userIdStr[i]);
				} catch (NumberFormatException e) {
					// 如果失败，设置为null
					request.setAttribute("userDeleteBooleanAll", null);
					// 跳转回原页面
					request.getRequestDispatcher("/admin/adminUser.jsp").forward(request, response);
					return;
				}
		    }
		    // 现在，userIds 数组中包含了 userIdStr 数组中的每个元素的整数值
			// 执行删除方法
			Boolean userDeleteBooleanAll = userService.deleteUser(userIds);
			//将数据存入
			request.setAttribute( "userDeleteBooleanAll",userDeleteBooleanAll);
		}
		// 跳转回原页面
		request.getRequestDispatcher("/admin/adminUser.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
